package com.example.springbootsecurityjwt.service.impl;

import com.example.springbootsecurityjwt.common.ResponseResult;
import com.example.springbootsecurityjwt.domain.LoginUser;
import com.example.springbootsecurityjwt.domain.User;
import com.example.springbootsecurityjwt.service.LoginServcie;
import com.example.springbootsecurityjwt.utils.JwtUtil;
import com.example.springbootsecurityjwt.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @program: SpringBoot-Security-JWT
 * @description: 登录实现类
 * @author: Coder_Pan
 * @create: 2022-03-22 13:05
 **/
@Service
public class LoginServcieImpl implements LoginServcie {
    final
    RedisCache redisCache;
    final
    AuthenticationManager authenticationManager;

    public LoginServcieImpl(AuthenticationManager authenticationManager, RedisCache redisCache) {
        this.authenticationManager = authenticationManager;
        this.redisCache = redisCache;
    }

    /**
     * 登录业务
     * @param user
     * @return
     */
    @Override
    public ResponseResult login(User user) {
        //创建UsernamePasswordAuthenticationToken对象  ==》 这个是Authentication的实现类        ==》根据用户名和密码生成token
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        //通过AuthenticationManager的authenticate方法来进行用户认证
        Authentication authenticate = authenticationManager.authenticate(token);
        //如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        //如果认证通过了，使用userid生成一个jwt，将jwt存入ResponseResult返回
        LoginUser loginUser =  (LoginUser)authenticate.getPrincipal();
        String userid = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userid);
        Map<String, String> map = new HashMap<>();
        map.put("token",jwt);
        //把完整的登录用户信息存入redis，userid作为key
        redisCache.setCacheObject("login:"+userid,loginUser);

        return ResponseResult.success(map);
    }

    /**
     * 退出登录业务
     * @return
     */
    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        //删除redis中的值
        redisCache.deleteObject("login:" + userId);
        return ResponseResult.success();
    }
}
